#!/usr/bin/env python

import sys, os, user
import pygtk
pygtk.require('2.0')
import gtk
from pysqlite2 import dbapi2 as sqlite
from databrain_db import Database

class AppMain:

    def __init__(self):
        self.load_database()
        self.main_window()

    def load_database(self, db_path=None):
        if db_path == None:
            db_home = os.path.join(user.home, '.databrain')
            db_path = os.path.join(db_home, 'db')
            if not os.path.exists(db_home):
                os.mkdir(db_home)
            if os.path.isfile(db_home):
                raise OSError('%s is a file, should be a dir' % (db_home))
        self.db = Database(db_path)

    def main_window(self):
        """Launches the application's main window."""

        ui_xml = ''' <ui>
            <menubar name="MenuBar">
                <menu action="File">
                    <menuitem action="Quit" />
                </menu>
                <menu action="Help">
                    <menuitem action="About" />
                </menu>
            </menubar>
        </ui>
        '''

        ui_actions = [

            # main menu - root
            ('File', None, '_File'),
            ('Help', None, '_Help'),

            # file menu
            ('Quit', gtk.STOCK_QUIT, '_Quit', None, 'Close the application', self.quit_cb),

            # help menu
            ('About', None, '_About'),
        ]

        window = gtk.Window()
        window.connect('destroy', lambda w: gtk.main_quit())
        window.set_size_request(400, 300)
        window.set_title('Data Brain')
        vbox = gtk.VBox()
        window.add(vbox)

        ui_manager = gtk.UIManager()
        accel_group = ui_manager.get_accel_group()
        window.add_accel_group(accel_group)
        action_group = gtk.ActionGroup('MainActionGroup')
        action_group.add_actions(ui_actions)
        ui_manager.insert_action_group(action_group, 0)
        ui_manager.add_ui_from_string(ui_xml)

        main_menu = ui_manager.get_widget('/MenuBar')
        vbox.pack_start(main_menu, False)

        notebook = gtk.Notebook()
        self.notebook = notebook
        notebook.set_tab_pos(gtk.POS_TOP)
        notebook.connect('switch_page', self.switch_page_cb)
        vbox.pack_start(notebook)

        tab_label = gtk.Label('Enter')
        remember_frame = self.get_remember_frame()
        notebook.append_page(remember_frame, tab_label)

        tab_label = gtk.Label('Search')
        search_frame = self.get_search_frame()
        notebook.append_page(search_frame, tab_label)

        tab_label = gtk.Label('Recent')
        recent_frame = self.get_recent_frame()
        notebook.append_page(recent_frame, tab_label)
        self.recent_tab_index = 2

        window.show_all()

    def get_remember_frame(self):
        frame = gtk.Frame()
        hbox = gtk.HBox()
        vbox = gtk.VBox()
        hbox2 = gtk.HBox()

        label = gtk.Label()
        label.set_markup("<span size='large'>Go ahead, enter something.</span>")
        vbox.pack_start(label, False, False, 10)

        entry = gtk.Entry()
        self.entry = entry
        entry.connect('key_press_event', self.entry_keydown_cb)
        hbox2.pack_start(entry)

        button = gtk.Button('Enter')
        button.connect('clicked', self.enter_button_cb)
        hbox2.pack_start(button, False, False)

        vbox.pack_start(hbox2, False, False, padding=10)
        hbox.pack_start(vbox, padding=40)
        frame.add(hbox)
        return frame

    def get_search_frame(self):
        frame = gtk.Frame()
        vbox = gtk.VBox()
        hbox = gtk.HBox()

        entry = gtk.Entry()
        self.search_entry = entry
        entry.connect('key_press_event', self.search_keydown_cb)
        hbox.pack_start(entry)

        button = gtk.Button('Search')
        button.connect('clicked', lambda w: self.do_search())
        hbox.pack_start(button, False, False)

        vbox.pack_start(hbox, False, False, padding=10)

        store = gtk.ListStore(int, str)
        self.search_store = store
        treeview = gtk.TreeView(store)
        cell = gtk.CellRendererText()
        tvcol = gtk.TreeViewColumn('Value', cell, text=1)
        treeview.append_column(tvcol)
        vbox.pack_start(treeview)

        frame.add(vbox)
        return frame

    def get_recent_frame(self):
        frame = gtk.Frame()
        store = gtk.ListStore(int, str)
        self.recent_store = store
        treeview = gtk.TreeView(store)
        cell = gtk.CellRendererText()
        tvcol = gtk.TreeViewColumn('Value', cell, text=1)
        treeview.append_column(tvcol)
        frame.add(treeview)
        return frame

    def quit_cb(self, action):
        gtk.main_quit()

    def enter_button_cb(self, widget):
        self.db.insert_data(self.entry.get_text())

    def entry_keydown_cb(self, widget, event):
        if event.keyval == gtk.keysyms.Return:
            self.db.insert_data(self.entry.get_text())

    def search_keydown_cb(self, widget, event):
        if event.keyval == gtk.keysyms.Return:
            self.do_search()

    def switch_page_cb(self, notebook, page, page_num):
        # if not defined(self.recent_tab_index): return
        try:
            self.recent_tab_index
        except AttributeError:
            return
        if page_num == self.recent_tab_index:
            self.populate_recent_list()

    def do_search(self):
        self.search_store.clear()
        search_str = self.search_entry.get_text()
        data = self.db.query_search_data(search_str)
        for row in data:
            self.search_store.append([row[0], row[1]])

    def populate_recent_list(self):
        self.recent_store.clear()
        data = self.db.query_recent_data()
        for row in data:
            self.recent_store.append([row[0], row[1]])

if __name__ == '__main__':
    app = AppMain()
    gtk.main()

